package DAL.JDBC;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import DAL.Entites.OrderItem;

public class OrderItemJDBC {
	Connection conn;
	String tableName = "orderitems"; 
	
	public OrderItemJDBC(Connection connection) {
		this.conn = connection;
	}
	
	public void insert(int OrderId, int GameId) {
		// this is for selecting db incase we do insert first
		// ((DriverManagerDataSource)dataSource).setUrl("jdbc:mysql://localhost:3306/TestData");
		String SQL = String.format("insert into %s values(%s, %s)",
				tableName, OrderId, GameId);
		
		try {
			Statement st = this.conn.createStatement();
			st.execute(SQL);
			st.close();
			System.out.println("Created Record");
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}
		return;
	}
	
	private OrderItem mapRow(ResultSet rs) throws SQLException {
		OrderItem orderItem = new OrderItem(rs.getInt("OrderId"), rs.getInt("GameId"));
		System.out.println("mapRow");

		return orderItem;
	}
	
	public List<OrderItem> listOrderItemsByOrderId(int OrderId) {
		List<OrderItem> ordersList = new ArrayList<OrderItem>();
		String SQL = String.format("select * from %s where OrderId = %s ", tableName, OrderId);
		try {
			Statement st = conn.createStatement();
			for (ResultSet rs = st.executeQuery(SQL); rs.next();) {
				ordersList.add(mapRow(rs));
			}
			st.close();
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}

		return ordersList;
	}
	
}
